import axios from "axios";

const api = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
  },
});

// 用户服务
export const userService = {
  // 注册或查找用户，智能重试
  registerOrFind: async (email: string, retry = 2) => {
    let lastError;
    for (let i = 0; i < retry; i++) {
      try {
        const response = await api.post("/user", { email });
        return response.data;
      } catch (err) {
        lastError = err;
        if (i < retry - 1) await new Promise((r) => setTimeout(r, 1000)); // 等待1秒再试
      }
    }
    throw lastError;
  },

  // 获取用户数据
  getUser: async (email: string) => {
    const response = await api.get(`/user/${email}`);
    return response.data;
  },
};

// 聊天服务
export const chatService = {
  // 获取聊天记录
  getChat: async (chatId: string) => {
    const response = await api.get(`/chat/${chatId}`);
    return response.data;
  },

  // 添加新消息
  addMessage: async (chatId: string, newMessage: any) => {
    const response = await api.post(`/chat/${chatId}/messages`, { newMessage });
    return response.data;
  },

  // 创建新聊天
  createChat: async (
    userId: string,
    chatTitle: string,
    initialMessage: any
  ) => {
    const response = await api.put("/chat/message", {
      userId,
      chatTitle,
      initialMessage,
    });
    return response.data;
  },
  //改变标题
  updateChatTitle: async (chatId: string, newTitle: string) => {
    const response = await api.put(`/chat/${chatId}/title`, { newTitle });
    return response.data;
  },

  //删除聊天
  deleteChat: async (chatId: string) => {
    const response = await api.delete(`/chat/${chatId}`);
    return response.data;
  },
};
